Skip to content


ai  101  pytorch  classification  nvidia  cuda  install  tensorrt  yolo  ardupilot  None  ros2  dds  micro ros  xrce  sitl  plugin  SITL  debug  rangefinder  pymavlink  mavros  gazebo  distance sensor  system_time  timesync  cmake  gtest  ctest  cpp  c++  format  fmt  multithreading  spdlog  camera  coordinate system  orb  matching  opencv  build  transformation  computer vision  homography  optical flow  of  trackers  cv  cyclonedds  eprosima  fastdds  simulation  config  ignition  bridge  sdf  tips  ign-transport  sensors  lidar  aptly  apt  encryption  pgp  docker  git  bundle  github  hooks  pre-commit  lxd  container  lxc  x11  profile  vscode  marpit  presentation  marp  markdown  mermaid  video  ffmpeg  gstreamer  cheat-sheet  sdp  v4l2loopback  gi  snippets  cheat Sheet  python  asyncio  future  click  cli  numpy  project  template  black  isort  docs  project document  docstrings  flake8  linter  git-hook  mypy  unittest  pytest  pylint  mock  iterator  generator  logging  tuple  namedtuple  typing  annotation  pyzmq  zmq  msgpack  action  namespace  remap  control2  ros2_control  gdb  qos  tag  plugins  msg  node  zero-copy  shm  tutorial  algorithm  calibration  diff  pid  dev  colcon  colcon_cd  rpi  arm  qemu  settings  behavior  plot  visualization  debugging  diagnostic  diagnostics  tutorials  gst  math  apm  rat_runtime_monitor  web  rosbridge  vue  binding  discovery  gazebo-classic  launch  spawn  cook  gps  imu  ray  gazebo_ros_ray_sensor  ultrsonic  range  ultrasonic  gazebo classic  wrench  effort  odom  ign  gz  xacro  ros_ign  diff_drive  odometry  joint_state  argument  OpaqueFunction  DeclareLaunchArgument  LaunchConfiguration  tmux  nav  slam  test  rclpy  executor  MultiThreadedExecutor  SingleThreadedExecutor  param  dynamic-reconfigure  service  client  setup.py  package.xml  parameter  parameters  custom  msgs  executers  pub  sub  rqt  rviz  rviz2  pose  marker  tf2  deb  package  setup  local_setup  rosdep  package manager  project settings  vcstool  cross-compiler  nano  texture  tmuxp  rootfs  embedded  zah  linux  rm  ubuntu  ip  ss  network  netstat  snap  deploy  ssh  systemd  mkdocs  extensions  socat  networking  serial  udp  tc  mtu  select  px4  robotics  kalman_filter  kalman  filter  control  todo  vscode-ext  json  yaml  schema  yocto  poky  world  gazebo_ros2_control  position_controller  effort_controller  velocity_controller  urdf  gazebo_ros_force  gazebo_ros_joint_state_publisher  robot_state_publisher  joint_state_publisher  projects  vrx  buoyancy 

Part1 - Simple PUB / SUB

Write simple ROS2 python package with publisher subscriber and usage ROS2 CLI tools


Publisher#

node source code#

Node source code
import rclpy
from rclpy.node import Node
from std_msgs.msg import String

class MinimalPublisher(Node):
    def __init__(self):
        super().__init__("minimal_publisher")
        self.publisher_ = self.create_publisher(String, "minimal", 10)
        timer_period = 1  # seconds
        self.timer = self.create_timer(timer_period, self.timer_callback)
        self.i = 0

    def timer_callback(self):
        msg = String()
        msg.data = f"pub simple: {self.i}"
        self.publisher_.publish(msg)
        self.get_logger().info(f'Publishing: "{msg.data}"')
        self.i += 1


def main(args=None):
    rclpy.init(args=args)
    minimal_publisher = MinimalPublisher()
    # Spin the node so the callback function is called.
    rclpy.spin(minimal_publisher)
    minimal_publisher.destroy_node()
    rclpy.shutdown()


if __name__ == "__main__":
    main()

setup.py#

  • Add entry point <node name>.<module name>:<entry func>
entry_points={
        'console_scripts': [
            "simple_pub = basic.simple_pub:main"
        ],
    }

package.xml#

  • Add this lines before <export> tag
  <exec_depend>rclpy</exec_depend>
  <exec_depend>std_msgs</exec_depend>

Note

exec_depend Declares a rosdep key or ROS package name that this package needs at execution-time


build and run#

Build
colcon build --symlink-install --packages-select basic
Source it
source install/setup.bash
Run
ros2 run basic simple_pub
output
[INFO] [1649181441.732282742] [minimal_publisher]: Publishing: "pub simple: 0"
[INFO] [1649181442.713229723] [minimal_publisher]: Publishing: "pub simple: 1"
[INFO] [1649181443.713351778] [minimal_publisher]: Publishing: "pub simple: 2"

cli#

ros2 topic#

# list
ros2 topic list
#result
/parameter_events
/rosout
/minimal

# info
ros2 topic info /minimal
# Result
Type: std_msgs/msg/String
Publisher count: 1
Subscription count: 0

# Echo
ros2 topic echo /minimal
# Result
data: 'pub simple: 110'
---
data: 'pub simple: 111'
---

topic verbose info#

verbose info
ros2 topic info -v /minimal
# Result
Type: std_msgs/msg/String

Publisher count: 1

Node name: minimal_publisher
Node namespace: /
Topic type: std_msgs/msg/String
Endpoint type: PUBLISHER
GID: 01.0f.d1.c7.10.ba.23.e1.01.00.00.00.00.00.11.03.00.00.00.00.00.00.00.00
QoS profile:
  Reliability: RMW_QOS_POLICY_RELIABILITY_RELIABLE
  Durability: RMW_QOS_POLICY_DURABILITY_VOLATILE
  Lifespan: 2147483651294967295 nanoseconds
  Deadline: 2147483651294967295 nanoseconds
  Liveliness: RMW_QOS_POLICY_LIVELINESS_AUTOMATIC
  Liveliness lease duration: 2147483651294967295 nanoseconds

Subscription count: 0

Subscriber#

node source code#

MinimalSubscriber Node source code
import rclpy
from rclpy.node import Node
from std_msgs.msg import String


class MinimalSubscriber(Node):
    def __init__(self):
        super().__init__("minimal_subscriber")

        # The node subscribes to messages of type std_msgs/String,
        # over a topic named: /minimal
        # The callback function is called as soon as a message is received.
        # The maximum number of queued messages is 10.
        self.subscription = self.create_subscription(
            String, "minimal", self.__sub_callback, 10
        )

    def __sub_callback(self, msg):
        self.get_logger().info(f"I heard: {msg.data}")


def main(args=None):
    rclpy.init(args=args)
    minimal_subscriber = MinimalSubscriber()
    rclpy.spin(minimal_subscriber)
    minimal_subscriber.destroy_node()
    rclpy.shutdown()


if __name__ == "__main__":
    main()

setup.py#

  • Add entry point
entry_points={
        'console_scripts': [
            "simple_sub = basic.simple_sub:main"
        ],
    }

build and run#

Build
colcon build --symlink-install --packages-select basic

cli#

  • Run subscriber node
Terminal1
ros2 run basic simple_sub
# Result after pub from terminal 2
[INFO] [1649213924.055190916] [minimal_subscriber]: I heard: hello
[INFO] [1649213925.036938799] [minimal_subscriber]: I heard: hello
Terminal2
# pub message
ros2 topic pub /minimal std_msgs/msg/String "{data: 'hello'}"

# pub only one message
ros2 topic pub -1 /minimal std_msgs/msg/String "{data: 'hello'}"

References#